import { JXDef } from "../../../conventions/JXCommon";
import { PRIORITY_VIEW } from "../../../Core/CoreDefine";
import { GCtrl } from "../../../Core/GCtrl";
import GChild from "../../../Core/GView/GChild";
import { CMsg, FRONT, ITEM_TYPE, LISTENTTYPE, RedpointEffect, RPointMask, TEXTURE_PREFIX } from "../../Common/Define";
import { VIEW_ID } from "../../Common/UI";
import { Res } from "../../Common/UIResources";
import GameMgr from "../../Logic/GameMgr";

const { ccclass, property, menu, executeInEditMode } = cc._decorator;
@ccclass @menu('View/Hero/HeroCardItem')

export default class HeroCardItem extends GChild {
    @property({
        type: cc.Label,
        tooltip: "英雄名字"
    })
    heroName: cc.Label = null;

    @property({
        type: cc.Node,
        tooltip: "星级"
    })
    star: cc.Node = null;

    @property({
        type: cc.Sprite,
        tooltip: "英雄图片"
    })
    heroImg: cc.Sprite = null;

    @property({
        type: cc.Sprite,
        tooltip: "英雄品级"
    })
    heroGrade: cc.Sprite = null;

    @property({
        type: cc.Node,
        tooltip: "上下阵"
    })
    setting: cc.Node = null;

    @property({
        type: cc.Sprite,
        tooltip: "英雄品级"
    })
    quality: cc.Sprite = null;

    @property({
        type: cc.Label,
        tooltip: "职业"
    })
    lab: cc.Label = null;

    @property({
        type: cc.Sprite,
        tooltip: "职业1"
    })
    labImg: cc.Sprite = null;

    @property({
        type: cc.Node,
        tooltip: "已上阵"
    })
    isBattleImg: cc.Node = null;

    @property({
        type: cc.Node,
        tooltip: "碎片数量"
    })
    fragment: cc.Node = null;

    @property({
        type: cc.Sprite,
        tooltip: "是否已解锁"
    })
    lockBtn: cc.Sprite = null;



    @property({
        type: cc.Button,
        tooltip: "跳转英雄详情页按钮"
    })
    jump: cc.Button = null;

    @property({
        type: cc.Button,
        tooltip: "跳转英雄获取碎片弹窗"
    })
    jumpChipView: cc.Button = null;


    @property(cc.Sprite) spt_icon: cc.Sprite = null;
    protected _touchMove: boolean = false;
    protected _iconShowNode: cc.Node = null;
    protected _touchBegin: boolean = false;
    protected _dragShowNode: cc.Node = null;
    private _sHeroData: SHeroDataRaw = null;
    private _rHeroData: IHeroData = null;
    protected _isDraging: boolean = false;
    private _canPutOn: boolean = false;
    private _seatNode: cc.Node[] = []
    protected _onSeat: boolean = false;
    private _index: number = 0;
    private _heroInBattle: number[] = [];
    private _chess = [null, '兵', '车', '马', '炮', "相", "士"];
    private _isListent: number = LISTENTTYPE.listent1;
    protected _isLock

    onGLoad() {
        GCtrl.ES.on(CMsg.client.home.onBattleItem, this, this.settingIsShow.bind(this));
        GCtrl.ES.on(CMsg.client.home.onHeroItem, this, this.render.bind(this));
        GCtrl.ES.on(CMsg.client.hero.onHeroLvUp, this, this.setRedPoint.bind(this), PRIORITY_VIEW);
        GCtrl.ES.on(CMsg.client.hero.onHeroBreach, this, this.setRedPoint.bind(this), PRIORITY_VIEW);
        GCtrl.ES.on(CMsg.client.hero.onHeroAddStar, this, this.setRedPoint.bind(this), PRIORITY_VIEW);
        GCtrl.ES.on(CMsg.client.equip.onEquipPutOn, this, this.setRedPoint.bind(this), PRIORITY_VIEW);
        GCtrl.ES.on(CMsg.client.equip.onEquipPutOff, this, this.setRedPoint.bind(this), PRIORITY_VIEW);
        GCtrl.ES.on(CMsg.client.equip.ondelEquip, this, this.setRedPoint.bind(this), PRIORITY_VIEW);

    }

    public onDisable() {
        this.node.targetOff(this);
    }

    public init(listData: SHeroDataRaw | IHeroData, index: number, isListent: number = LISTENTTYPE.listent1) {
        this._isListent = isListent;
        if (this._isListent == LISTENTTYPE.listent3) {
            this.jump.node.active = true;
            this.jump.interactable = true;
        }
        this._index = index;
        let data = listData as any;
        if (!data.tableId) {
            this._sHeroData = listData as SHeroDataRaw;
            this._rHeroData = null;
            this.star.active = false;
            this.isBattleImg.active = false;
            // this.heroName.node.y = -101;;
        } else {
            this._rHeroData = listData as IHeroData;
            this._sHeroData = GameMgr.heroData.getRaw(this._rHeroData.tableId);
            let bool = GameMgr.rHeroData.checkHeroIsInBattle(this._rHeroData.tableId);

            if (this._isListent == LISTENTTYPE.listent2) { } else {
                this.isBattleImg.active = bool;
            }
            if (bool) {
                // this.heroName.node.y = -100;
            } else {
                // this.heroName.node.y = -101;;
            }
            this.addStar();
        }
        this.setting.active = false;
        isListent == LISTENTTYPE.listent1 && this.initEvent()
        this.checkStatus();
        this.setView();
        this.Unlock();
        this.assetImpl.spriteFrame(this.heroImg, Res.texture.hero.hero + this._sHeroData.icon);
        this.setRedPoint();
    }

    protected setRedPoint() {
        if (this._rHeroData) {
            if (this.node.parent.name === "heroLayout") {
                let isLvUp = GameMgr.heroMgr.checkHeroCanGrow(this._rHeroData.tableId, false);
                let isTuPo = GameMgr.heroMgr.checkHeroCanGrow(this._rHeroData.tableId, true);
                let isAddStart = GameMgr.heroMgr.checkHeroCanAddStar(this._rHeroData.tableId)
                let havaBaseWear = GameMgr.heroMgr.checkHeorBastEquip(this._rHeroData);

                GameMgr.redMgr.setRPointView(this.node, this.node, (isLvUp || isTuPo || isAddStart || havaBaseWear), RedpointEffect.REDPOINT);
            } else if (this.node.parent.name === "blessPage") {
                let isSync = GameMgr.itemMgr.checkEquipCanSync(this._rHeroData);
                let isLvup = GameMgr.itemMgr.checkHeroEquipCanLvUp(this._rHeroData);
                GameMgr.redMgr.setRPointView(this.node, this.node, (isSync || isLvup), RedpointEffect.REDPOINT);
            }
        } else {
            if (this.node.parent.name === "heroLayout") {
                let canUnlock = GameMgr.heroMgr.checkHeroCanUnlockByChip(this._sHeroData.id);
                GameMgr.redMgr.setRPointView(this.lockBtn.node, this.lockBtn.node, canUnlock, RedpointEffect.REDPOINT);
            }
            GameMgr.redMgr.setRPointView(this.node, this.node, false, RedpointEffect.REDPOINT);
        }
    }

    protected addStar() {
        this.star.active = true;
        //let star = this._rHeroData ? this._rHeroData.star : this._sHeroData.birthStar;
        let star = this._rHeroData.star;
        let obj = GameMgr.heroMgr.getChipNeedByStar(star);
        for (let i = 0; i < this.star.children.length; i++) {
            if (i <= obj.count - 1) {
                this.star.children[i].color = cc.Color.WHITE;
                this.star.children[i].active = true;
                this.assetImpl.spriteAtlasFrame(this.star.children[i].getComponent(cc.Sprite), Res.texture.views.icon, 'icon_star' + (obj.lv + 1));

            } else {
                this.star.children[i].active = false;
            }
        }
    }

    /**设置视图 */
    protected setView() {
        this.heroName.string = this._sHeroData.name + '';
        this.lab.string = this._chess[this._sHeroData.type] + '';
        let atlas = Res.texture.map.quality;
        let trait = this._rHeroData ? this._rHeroData.trait : this._sHeroData.trait;
        this.assetImpl.spriteAtlasFrame(this.labImg, atlas, TEXTURE_PREFIX.type + this._sHeroData.type);
        this.assetImpl.spriteAtlasFrame(this.quality, atlas, TEXTURE_PREFIX.quality + trait);
    }

    /**解锁 */
    protected lock() {
        let awardArr: number[][] = [[0, 0, 0]];
        awardArr[0][0] = this._sHeroData.id;
        awardArr[0][1] = ITEM_TYPE.HERO;
        awardArr[0][2] = 1;
        let unlockStar: number = GameMgr.heroData.getRaw<SHeroDataRaw>(this._sHeroData.id).unlockStar;
        GameMgr.jumpToMgr.jumpGoTo(VIEW_ID.rewardCtrl, awardArr);
        GCtrl.ES.emit(CMsg.client.bag.onBagItemChange, [[this._sHeroData.id, ITEM_TYPE.PROP, -unlockStar]])
        GameMgr.redMgr.sendValueSettingMsg(RPointMask.RPM_Hero_UnLock, false);
    }

    /**跳转英雄详情页  跳转加持界面*/
    protected childClick() {
        if (this._isListent == LISTENTTYPE.listent2) {
            if (this._rHeroData) {
                // console.log('跳转英雄详情页');
                GameMgr.jumpToMgr.jumpGoTo(VIEW_ID.detailsCtrl, this._rHeroData, this._sHeroData);
            } else {
                // console.log('跳转英雄碎片');
                let item = GameMgr.RBagData.getMegreItems(this._sHeroData.id, ITEM_TYPE.PROP).num;
                let isCanLock = item >= this._sHeroData.unlockStar;
                if (!isCanLock) {
                    let cost = [this._sHeroData.id, ITEM_TYPE.PROP, 1];
                    GameMgr.jumpToMgr.jumpGoTo(VIEW_ID.currencyFrame, cost, 1);
                } else {
                    this.jumpChipView.node.active = false;
                    this.lock();
                }
            }
        }

        if (this._isListent == LISTENTTYPE.listent3) {
            if (this._rHeroData) {
                // console.log('跳转加持界面');
                let level = GameMgr.lUserData.level;
                let aidOpen = GameMgr.systemConfig.value(JXDef.SYS_CONFIG_KEY.aidOpen);
                if (level >= aidOpen) {
                    // GameMgr.sdkMgr.umaSetPoint(JXDef.umaPoint.bless, { msg: this._sHeroData.name + "进入加持界面" });
                    GameMgr.jumpToMgr.jumpGoTo(VIEW_ID.blessCtrl, this._rHeroData, this._sHeroData);
                } else {
                    let str = "通过第" + aidOpen + "关开启合成强化界面";
                    GameMgr.uiMgr.showToast(str);
                    // GameMgr.uiMgr.showToast(JXLocales.tip.level); 
                }
            }
        }
    }

    public Unlock() {
        let item = GameMgr.RBagData.getMegreItems(this._sHeroData.id, ITEM_TYPE.PROP).num;
        this.jumpChipView.node.active = false;
        if (this._rHeroData) {
            // this.heroName.node.y = -100;
            this.lockBtn.node.parent.active = false;
            this.lockBtn.node.getChildByName('tan').active = false;
            this.fragment.active = false;
            if (this._isListent == LISTENTTYPE.listent2) {
                this.jump.node.active = true;
                this.jump.interactable = true;
            }
        } else {
            this.lockBtn.node.parent.active = true;
            let isCanLock = item >= this._sHeroData.unlockStar;
            this.lockBtn.node.getComponent(cc.Button).interactable = isCanLock;
            let img = isCanLock ? "lock" : "unlock";
            if (!isCanLock) {
                this.jumpChipView.node.active = true;
                this.lockBtn.node.getChildByName('tan').active = false;
            } else {
                this.lockBtn.node.getChildByName('tan').active = true;
            }
            this.assetImpl.spriteAtlasFrame(this.lockBtn, Res.texture.views.heroDetail, img);
            this.fragment.active = true;
            this.fragment.getChildByName('lab').getComponent(cc.Label).string = item + '/' + this._sHeroData.unlockStar;
        }

    }


    /**初始触摸事件 */
    protected initEvent() {
        this.node.on(cc.Node.EventType.TOUCH_START, this._onTouchStar, this);
        this.node.on(cc.Node.EventType.TOUCH_MOVE, this._onTouchMove, this);
        this.node.on(cc.Node.EventType.TOUCH_END, this._onTouchEnd, this);
        this.node.on(cc.Node.EventType.TOUCH_CANCEL, this._onTouchCancel, this);
    }


    public checkStatus() {
        if (!this._sHeroData) {
            this._canPutOn = false;
        } else {
            this._canPutOn = true;
        }
    }

    public setSeatNode(node: cc.Node) {
        node.children.forEach((node) => {
            this._seatNode.push(node)
        });
    }

    public destroyDragNode() {
        if (cc.isValid(this._dragShowNode)) {
            this._dragShowNode.destroy();
            this._dragShowNode = null;
        }
    }

    private _onTouchStar(event: cc.Event.EventTouch) {
        GCtrl.ES.emit(CMsg.client.home.onBattleItem, this._index);
        this._touchMove = false;
        this.destroyDragNode();
        this._touchBegin = true;
        event.stopPropagation();
    }

    private _onTouchMove(event: cc.Event.EventTouch) {
        if (!this._canPutOn) {
            return;
        }
        let deltaMove = event.getLocation().sub(event.getStartLocation());
        if (!this._isDraging) {
            this._isDraging = true;
        }
        if (deltaMove.mag() > 7 && this._isDraging) {
            let parent = this._seatNode[0].parent;
            if (!this._touchMove) {
                this._touchMove = true;
                this._dragShowNode = cc.instantiate(this.spt_icon.node);
                this._dragShowNode.getComponent(cc.Sprite).spriteFrame = this.heroImg.spriteFrame;
                this._dragShowNode.active = true;
                this._dragShowNode.parent = this._seatNode[0].parent;
                let localPos: cc.Vec2 = parent.convertToNodeSpaceAR(event.getLocation());
                this._dragShowNode.setPosition(localPos);
            } else {
                let worldPos = event.getLocation();
                let localPos: cc.Vec2 = parent.convertToNodeSpaceAR(worldPos);
                this._dragShowNode.setPosition(localPos);
                this.node.parent.parent.parent.getComponent(cc.ScrollView).enabled = false;
                let result = this.checkIsEnter(worldPos, this._sHeroData);
                if (result.isEnter) {
                    if (!this._onSeat) {
                        // console.log("进入区域", result.index);
                        this._onSeat = true;
                    }
                } else {
                    if (this._onSeat) {
                        // console.log("离开区域");
                        this._onSeat = false;
                    }
                }

            }
        }
    }

    public checkIsEnter(worldPos, itemData: SHeroDataRaw) {
        let index = null;
        let isEnter = false;
        for (let i = 0; i < this._seatNode.length; i++) {
            let node = this._seatNode[i];
            isEnter = node.getBoundingBoxToWorld().contains(worldPos)
            if (isEnter) {
                index = i;
                break;
            }
        }
        return { isEnter, index, itemData }
    }

    public _onTouchEnd(event: cc.Event.EventTouch, isCancel = false) {
        let worldPos = event.getLocation();
        this.destroyDragNode();
        if (this._touchMove) {
            let result = this.checkIsEnter(worldPos, this._sHeroData);
            if (result.isEnter) {
                console.log("命中", result.index);
                this.replaceData(Number(result.itemData.id), result.index);
            } else {
                console.log("弹开未选中");
            }
        } else {
            if (isCancel == false) {
                console.log("点击");

                this.settingBtn();
            }
        }
        this.node.parent.parent.parent.getComponent(cc.ScrollView).enabled = true;
        this._touchBegin = false;
        this._touchMove = false;
        this._onSeat = false;
        this._isDraging = false;
    }

    /**命中图标上阵 */
    private replaceData(id: number, iconIndex: number) {
        this._heroInBattle = GameMgr.rHeroData.heroIdsInBattle;
        this._heroInBattle.forEach((value, index) => {
            if (iconIndex == index) {
                this._heroInBattle[index] = id;
                let str = GameMgr.lUserData.heroNames(id);
                GameMgr.sdkMgr.umaSetPoint(JXDef.umaPoint.heroBattle, { msg: str })
                GameMgr.rHeroData.heroIdsInBattle = this._heroInBattle;
                this.settingBtn();
                GCtrl.ES.emit(CMsg.client.home.onHeroItem, [FRONT.battle, this._rHeroData.tableId]);
                GCtrl.ES.emit(CMsg.client.home.onheroBattleItem);

                if (this._isListent == LISTENTTYPE.listent2) { } else {
                    this.isBattleImg.active = true;
                }

                // this.heroName.node.y = -100;
            }
            else {
                if (value == id) {
                    this._heroInBattle[index] = -1;
                    GameMgr.rHeroData.heroIdsInBattle = this._heroInBattle;
                    GCtrl.ES.emit(CMsg.client.home.onheroBattleItem);
                    // GCtrl.ES.emit(CMsg.client.home.onHeroItem, FRONT.Lower);
                    // this.isBattleImg.active = false;
                }
            }
        })
    }

    private _onTouchCancel(event: cc.Event.EventTouch) {
        this._onTouchEnd(event, true);
        // this.node.parent.parent.parent.getComponent(cc.ScrollView).enabled = true;
        // this._touchBegin = false;
        // this._touchMove = false;
        // this._onSeat = false;
        // this._isDraging = false;
        // this.destroyDragNode();
    }

    private render(data, arr) {
        let obj: front = {
            isbattle: arr[0],
            id: arr[1],
        }
        this.Unlock();
        if (this._rHeroData) {
            if (this._rHeroData.tableId == obj.id && obj.isbattle == FRONT.Lower) {
                this.setting.active = false;
                this.isBattleImg.active = false;
                // this.heroName.node.y = -101;
            }
            else {
                if (this._rHeroData.tableId == obj.id && obj.isbattle == FRONT.battle) {
                    if (this._isListent == LISTENTTYPE.listent2) {

                    } else {
                        this.isBattleImg.active = true;
                    }
                    // this.heroName.node.y = -100;
                }
            }
        }
    }

    private settingIsShow(index: number) {
        if (this._index != index) {
            this.setting.active = false;
        }
    }

    /**弹出上下阵按钮 详情 */
    private settingBtn() {
        let bool = false;
        bool = this.existence();
        this.setting.active = bool;
    }

    /**上下阵 */
    private isBattle() {
        let bool = false;
        bool = this.existence();
        this.brush(Number(this._sHeroData.id), bool);
    }

    /**判断一个位置之前是否存在英雄 */
    private existence() {
        let bool = false;
        GameMgr.rHeroData.heroIdsInBattle.forEach((value, index) => {
            if (bool) {
                return;
            }
            if (!bool) {
                if (value == Number(this._sHeroData.id)) {//存在同id英雄
                    bool = true;
                } else {
                    bool = false;
                }
            }
        })
        return bool;
    }

    /**点击下阵按钮刷新图片以及数据 */
    private brush(id, Battle: boolean) {
        let bool = false;
        let rHeroData = GameMgr.rHeroData.heroIdsInBattle;
        rHeroData.forEach((value, index) => {
            if (Battle) {
                if (!bool) {
                    // console.log("brush", this._index);
                    if (value == Number(this._sHeroData.id)) {
                        rHeroData[index] = -1;
                        this.setting.active = false;
                        this.isBattleImg.active = false;
                        GCtrl.ES.emit(CMsg.client.home.onHeroItem, [FRONT.Lower, this._rHeroData.tableId]);
                        GCtrl.ES.emit(CMsg.client.home.onheroBattleItem);
                        bool = true;
                        return;
                    }
                }
            }
        })
        GameMgr.rHeroData.heroIdsInBattle = rHeroData;
    }
}   